<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
	<th:block th:include="include :: header('文件列表')" />
	<link rel="stylesheet" th:href="@{/plugins/webuploader/0.1.5/webuploader.css}"/>
</head>
<body class="gray-bg">
<section class="content">
	<div class="box box-default" style="margin-bottom: 10px;">
		<div class="box-body">
			<div class="col-sm-12 search-collapse">
				<form id="formSearch">
					<div class="select-list">
						<ul>
							<li>关键字: <input type="text" id="originalName"
								name="originalName" placeholder="请输入原文件名" />
							</li>
							<li>云存储: <select id="ossType">
									<option value="">请选择</option>
									<option value="0">本地</option>
									<option value="1">七牛云</option>
									<option value="2">阿里云</option>
									<option value="3">腾讯云</option>
							</select>
							</li>
							<li><a class="btn btn-primary btn-rounded btn-sm"
								id="btn_query"><i class="fa fa-search"></i>&nbsp;搜索</a> <a
								class="btn btn-warning btn-rounded btn-sm" id="btn_reset"><i
									class="fa fa-refresh"></i>&nbsp;重置</a></li>
						</ul>
					</div>
				</form>
			</div>
		</div>
	</div>
	<div class="jax-box-table">
		<div id="toolbar">
			<button id="upload-container" type="button"
				class="btn btn-primary btn-sm">
				<i class="fa fa-upload" aria-hidden="true"></i>上传
			</button>
			<shiro:hasPermission name="sysJob:batchDelete">
				<button id="btn_batch_delete" type="button"
					class="btn btn-danger btn-sm">
					<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除
				</button>
			</shiro:hasPermission>
			<button id="upload-set" type="button" class="btn btn-info btn-sm"
				onclick="setFilestorage()">
				<i class="fa fa-cogs" aria-hidden="true"></i> 文件存储设置
			</button>
		</div>
		<div class="my-gallery" itemscope
			itemtype="http://schema.org/ImageGallery">
			<table id="table"></table>
		</div>
	</div>
	<button id="picker" style="display: none;">点击上传文件</button>
</section>
<th:block th:include="include :: footer" />
<script th:src="@{/plugins/webuploader/0.1.5/webuploader.js}"></script>
<script>
    var columns=[
        {checkbox: true },
        {
            field: 'originalName',
            title: '原文件名',
            align: "center",
            valign: "middle",
        },
        {
            field: 'fileFullPath',
            title: '文件地址',
            align: "center",
            valign: "middle",
        },
        {
            field: 'ossType',
            title: '云存储',
            align: "center",
            valign: "middle",
           	formatter: function(value, row, index) {
            	var ossType = "";
                if(value===0){
                    ossType="本地";
				}else if(value===1){
                    ossType="七牛云";
                }else if(value===2){
                    ossType="阿里云";
                }else if(value===3){
                    ossType="腾讯云";
                }
                return ossType;
            }
        },
        {
            field: 'fileType',
            title: '文件类型',
            align: "center",
            valign: "middle",
        },
        {
            field: 'fileSize',
            title: '文件大小',
            align: "center",
            valign: "middle",
        },
        {
            field: 'createTime',
            title: '创建时间',
            align: "center",
            valign: "middle",
        },
        {
            field : 'operation',
            title : '操作',
            align : "center",
            valign: "middle",
            formatter : function(value, row, index) {
            	var fileUrl = encodeURIComponent(row.fileFullPath);
            	var shtml = '';
            	shtml += '<a class="btn btn-default btn-xs cursor-pointer" href="javascript:;" onclick="viewFile(\''+ fileUrl +'\', \''+ row.fileType +'\')"><i class="fa fa-eye"></i> 预览</a> ';
            	shtml += '<a class="btn btn-success btn-xs cursor-pointer" href="javascript:;" onclick="downloadFile(\''+ fileUrl +'\', \''+ row.originalName +'\')"><i class="fa fa-download"></i> 下载</a> ';
            	shtml += '<a class="btn btn-danger btn-xs cursor-pointer" href="javascript:;" onclick="deleteFile('+ row.fileId +')"><i class="fa fa-remove"></i> 删除</a> ';
            	return shtml;
            }
        }
    ];
    var options={
        id:"#table",
        url: '/sysfile/list',
        columns: columns,
        queryParams: queryParams
    }
    $.table.initTable(options);
  	//查询参数
    function queryParams(params) {
        var temp = { //这里的键的名字和控制器的变量名必须一致，这边改动，控制器也需要改成一样的
            limit : params.limit, //页面大小
            offset : params.offset, //页码
            ossType: $("#ossType").val(),
            originalName: $("#originalName").val()
        };
        return temp;
    }
    /*查询*/
    $("#btn_query").click(function(){
    	$.table.refreshTable();
    });
    /*重置*/
	$("#btn_reset").click(function() {
		$.common.clearForm("formSearch");
		$.table.refreshTable();
	});
    
    // 预览图片
    function viewFile(url, extName) {
    	var url = "/sysfile/common/fileViwe?extName="+ extName + "&fileUrl=" + decodeURIComponent(url);
	    width = 800;
	    height = ($(window).height() - 20);
	    layer.open({
	        type: 2,
	        maxmin: false,
	        shadeClose: true,
	        title: "文件预览",
	        fix : false, // 不固定
	        area: [width + "px", height + "px"],
	        content: url
	    });
    }
    
    // 下载
    function downloadFile(url, fileName){
    	var judgeDiv = document.getElementById("dwDiv");
        if(judgeDiv!=null){
            document.body.removeChild(judgeDiv);
        }
        var divObj = document.createElement("div");
        divObj.id="dwDiv";
        var aObj = document.createElement("a");
        aObj.href= "/sysfile/common/download?fileUrl=" + decodeURIComponent(url) + "&fileName=" + fileName;
        aObj.id = "hrefFile";
        divObj.appendChild(aObj);
        document.body.appendChild(divObj);
        document.getElementById("hrefFile").click();
        judgeDiv = document.getElementById("dwDiv");
        if(judgeDiv!=null){
            document.body.removeChild(judgeDiv);
        }
    }
    // 删除
    function deleteFile(value) {
    	$.modal.confirm("确定删除该文件吗？",function () {
    		$.common.postAjax("/sysfile/delete", {"fileIdStr": value}, function (data) {
				if (data.status === 200) {
					$.table.refreshTable();
					toastr.success(data.msg);
				} else {
					toastr.error(data.msg);
				}
			})
        })
    }
  	//批量删除
    $("#btn_batch_delete").click(function(){
        var checkedRows= $.table.selectMutiData("#table");
        if(checkedRows!=false){
        	$.modal.confirm("确定删除选中的"+checkedRows.length+"条记录？",function () {
                var fileIdStr="";
                $.each(checkedRows, function (i, item) {
                	fileIdStr += (item.fileId+",");
                })
                fileIdStr = fileIdStr.substring(0,fileIdStr.length-1);
                $.common.postAjax("/sysfile/delete",{"fileIdStr":fileIdStr},function(data){
                    if(data.status==200){
                    	$.table.refreshTable();
                    	toastr.success(data.msg);
                    } else {
                    	toastr.error(data.msg);
                    }
                })
            })
        }
    });

    /*存储设置*/
    function setFilestorage() {
    	$.modal.dialog_open("存储设置", "/sysfile/setStorage");
    }
    
    $('#upload-container').click(function(event) {
        $("#picker").find('input').click();
    });
	
	var uploader = WebUploader.create({
        auto: true,// 选完文件后，是否自动上传。
        server: '/upload/upload',// 文件接收服务端。
        dnd: '#upload-container',
        pick: '#picker',// 内部根据当前运行是创建，可能是input元素，也可能是flash. 这里是div的id
        multiple: true, // 选择多个
        threads: 5, // 上传并发数。允许同时最大上传进程数。
        method: 'POST', // 文件上传方式，POST或者GET。
        fileSizeLimit: 1024*1024*100*100, //验证文件总大小是否超出限制, 超出则不允许加入队列。
        fileSingleSizeLimit: 1024*1024*100, //验证单个文件大小是否超出限制, 超出则不允许加入队列。
        fileVal:'file', // [默认值：'file'] 设置文件上传域的name。
    });

    uploader.on('fileQueued', function(file) {
        // 选中文件时要做的事情，比如在页面中显示选中的文件并添加到文件列表，获取文件的大小，文件类型等
        console.log(file.name);
    });

    uploader.on('uploadProgress', function(file, percentage) {
        console.log(percentage * 100 + '%');
    });

    uploader.on('uploadSuccess', function(file, response) {
       	toastr.success("上传成功");
    });

    uploader.on('uploadError', function(file) {
    	toastr.error("上传失败");
    });
    
    uploader.on('uploadComplete', function(file) {
    	$.table.refreshTable();
    });
</script>
</body>
</html>